package com.phuoc.activities;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.annotation.TargetApi;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.phuoc.dao.EstablishmentDAO;
import com.phuoc.dao.TypeOfEstablishmentDAO;
import com.phuoc.dao.TypeOfFoodDAO;
import com.phuoc.entities.Establishment;

@TargetApi(9)
public class DetailsEstablishment extends CustomWindow {

	// DAO
	private EstablishmentDAO estabDataSource;
	private TypeOfEstablishmentDAO typeEstabDataSource;
	private TypeOfFoodDAO typeFoodDataSource;

	// layout
	private TextView txtEstabName;
	private TextView txtTypeOfEstab;
	private TextView txtTypeOfFood;
	private TextView txtLocation;
	private TextView txtDate;
	private TextView txtMeal;
	private TextView txtCost;
	private TextView txtCost1;
	private RatingBar rateService;
	private RatingBar rateAtmosphere;
	private RatingBar rateFood;
	private RatingBar rateOverall;
	private TextView txtComments;
	private LinearLayout layoutBtnSaveAndCancel;
	private LinearLayout layoutBtnAddAdvance;
	private LinearLayout layoutAdvanceDetails;

	// Dialog
	private Dialog dialogRate;
	private Dialog dialogTime;
	private Dialog dialogMeal;
	private Dialog dialogCost;
	private Dialog dialogWaiting;
	private Handler handler;

	// Rating
	private RatingBar ratingEstab;

	// Data advance details
	private Establishment estab;
	private String id;
	private float serviceScore = 0;
	private float atmosphereScore = 0;
	private float foodScore = 0;
	private float overallScore = 0;
	private String date;
	private String typeOfMeal = "Breakfast";
	private float cost = 0;
	private String comments;
	private boolean resultUpdate = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_details);
		this.setWindowTitle("Details Establishment");

		// Get Id from establishment activity
		id = getIntent().getExtras().getString("id");

		// Initial DAO
		estabDataSource = new EstablishmentDAO(this);
		estabDataSource.open();
		typeEstabDataSource = new TypeOfEstablishmentDAO(this);
		typeEstabDataSource.open();
		typeFoodDataSource = new TypeOfFoodDAO(this);
		typeFoodDataSource.open();

		// Find view
		txtEstabName = (TextView) findViewById(R.id.txtEstabName);
		txtTypeOfEstab = (TextView) findViewById(R.id.txtTypeOfEstab);
		txtTypeOfFood = (TextView) findViewById(R.id.txtTypeFood);
		txtLocation = (TextView) findViewById(R.id.txtLocation);
		txtDate = (TextView) findViewById(R.id.txtDate);
		txtMeal = (TextView) findViewById(R.id.txtTypeOfMeal);
		txtCost = (TextView) findViewById(R.id.txtCost);
		txtCost1 = (TextView) findViewById(R.id.txtCost1);
		rateService = (RatingBar) findViewById(R.id.viewRateService);
		rateAtmosphere = (RatingBar) findViewById(R.id.viewRateAtmosphere);
		rateFood = (RatingBar) findViewById(R.id.viewRateFood);
		rateOverall = (RatingBar) findViewById(R.id.viewRateOverall);
		txtComments = (TextView) findViewById(R.id.txtComments);
		layoutBtnSaveAndCancel = (LinearLayout) findViewById(R.id.layoutBtnSaveAndCancel);
		layoutBtnAddAdvance = (LinearLayout) findViewById(R.id.layoutBtnAddAdvance);
		layoutAdvanceDetails = (LinearLayout) findViewById(R.id.layoutAdvanceDetail);

		// Find dialog
		dialogRate = new Dialog(this);
		dialogRate.setContentView(R.layout.rate);
		ratingEstab = (RatingBar) dialogRate.findViewById(R.id.ratingEstab);

		dialogTime = new Dialog(this);
		dialogTime.setContentView(R.layout.time);

		dialogMeal = new Dialog(this);
		dialogMeal.setContentView(R.layout.meal);

		dialogCost = new Dialog(this);
		dialogCost.setContentView(R.layout.cost);
		
		handler = new  Handler();

		// Display info to View
		displayInfo();

		// Cancel Dialog event clicked
		cancelDialogClicked();

		// Set Dialog Time event clicked
		setTime();

		// Set Meal event clicked
		selectTypeOfMeal();

		// Set Cost event clicked
		setCost();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_details, menu);
		return true;
	}

	@Override
	protected void onPause() {
		estabDataSource.close();
		typeEstabDataSource.close();
		typeFoodDataSource.close();
		super.onPause();
	}

	@Override
	protected void onResume() {
		estabDataSource.open();
		typeEstabDataSource.open();
		typeFoodDataSource.open();
		displayInfo();
		super.onResume();
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_edit:
			Intent intent = new Intent(DetailsEstablishment.this,
					EditEstablishActivity.class);
			intent.putExtra("id", id);
			startActivity(intent);
			break;

		default:
			break;
		}
		return super.onMenuItemSelected(featureId, item);
	}

	private void displayInfo() {
		// get establishment
		estab = estabDataSource.getEstablishmentById(id);

		// Display Name to View
		txtEstabName.setText(estab.getName());

		// Display Type of Estab to View
		txtTypeOfEstab.setText(typeEstabDataSource.getNameById(estab
				.getIdTypeOfEstablishment()));

		// Display Type of Food to View
		txtTypeOfFood.setText(typeFoodDataSource.getNameById(estab
				.getIdTypeOfFood()));

		// Display Location to View
		txtLocation.setText(estab.getLocation());

		// Display date review
		if (estab.getDateReview() != null && !estab.getDateReview().isEmpty())
			txtDate.setText(estab.getDateReview());

		// Display type of meal
		if (estab.getTypeOfMeal() != null && !estab.getTypeOfMeal().isEmpty())
			txtMeal.setText(estab.getTypeOfMeal());

		// Display cost
		FrameLayout layoutCost = (FrameLayout) findViewById(R.id.layoutCost);
		layoutCost.setVisibility(FrameLayout.GONE);
		if (estab.getCost() > 0) {
			txtCost.setText(Float.toString(estab.getCost()) + " US$");
			txtCost.setVisibility(TextView.VISIBLE);
		} else {
			txtCost.setVisibility(TextView.GONE);
		}

		// Display rate service
		rateService.setRating(estab.getRateService());

		// Display rate atmosphere
		rateAtmosphere.setRating(estab.getRateAtmosphere());

		// Display rate food
		rateFood.setRating(estab.getRateFood());

		// Display rate overall
		rateOverall.setRating(estab.getRateOverall());

		// Display comments
		LinearLayout layoutComments = (LinearLayout) findViewById(R.id.layoutComments);
		EditText edtComments = (EditText) findViewById(R.id.edtComments);
		if (estab.getComment() != null && !estab.getComment().isEmpty()) {
			txtComments.setText(estab.getComment());
			layoutComments.setVisibility(LinearLayout.VISIBLE);
			edtComments.setVisibility(LinearLayout.GONE);
		} else {
			layoutComments.setVisibility(LinearLayout.GONE);
			edtComments.setVisibility(LinearLayout.VISIBLE);
		}

		// advance details is exists, hide button 'Add advance'
		if (estab.getRateService() > 0) {
			layoutAdvanceDetails.setVisibility(LinearLayout.VISIBLE);
			layoutBtnAddAdvance.setVisibility(LinearLayout.GONE);
			enableRateClick(false);
		} else {
			layoutAdvanceDetails.setVisibility(LinearLayout.GONE);
			layoutBtnSaveAndCancel.setVisibility(LinearLayout.GONE);
			layoutBtnAddAdvance.setVisibility(LinearLayout.VISIBLE);
		}
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnAddAdvance:
			// hide button Save and Cancel, display button Add Advance
			layoutBtnAddAdvance.setVisibility(LinearLayout.GONE);
			layoutBtnSaveAndCancel.setVisibility(LinearLayout.VISIBLE);
			// show EditText Comments
			EditText edtComments = (EditText) findViewById(R.id.edtComments);
			edtComments.setVisibility(EditText.VISIBLE);
			LinearLayout layoutComments = (LinearLayout) findViewById(R.id.layoutComments);
			layoutComments.setVisibility(LinearLayout.VISIBLE);
			// Show date now in field Date Review
			date = getDateNow();
			txtDate.setText(date);
			// Show field COST
			FrameLayout layoutCost = (FrameLayout) findViewById(R.id.layoutCost);
			layoutCost.setVisibility(FrameLayout.VISIBLE);
			// Show layout advance details
			layoutAdvanceDetails.setVisibility(LinearLayout.VISIBLE);
			// Allow to rate
			enableRateClick(true);
			break;

		case R.id.layoutService:
			dialogRate.setTitle("Rate Service");
			ratingEstab.setRating(serviceScore);

			// submit rating
			Button btnSubmitService = (Button) dialogRate
					.findViewById(R.id.btnSubmit);
			btnSubmitService.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					serviceScore = ratingEstab.getRating();
					ratingEstab.setRating(0);
					rateService.setRating(serviceScore);
					dialogRate.dismiss();
				}
			});

			// Hide error
			FrameLayout layoutRateService = (FrameLayout) findViewById(R.id.layoutService);
			layoutRateService.setBackgroundResource(R.drawable.border);

			dialogRate.show();
			break;

		case R.id.layoutAtmosphere:
			dialogRate.setTitle("Rate Atmosphere");
			ratingEstab.setRating(atmosphereScore);

			// submit rating
			Button btnSubmitAtmosphere = (Button) dialogRate
					.findViewById(R.id.btnSubmit);
			btnSubmitAtmosphere.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					atmosphereScore = ratingEstab.getRating();
					ratingEstab.setRating(0);
					rateAtmosphere.setRating(atmosphereScore);
					dialogRate.dismiss();
				}
			});

			// Hide error
			FrameLayout layoutRateAtmosphere = (FrameLayout) findViewById(R.id.layoutAtmosphere);
			layoutRateAtmosphere.setBackgroundResource(R.drawable.border);

			dialogRate.show();
			break;

		case R.id.layoutFood:
			dialogRate.setTitle("Rate Food");
			ratingEstab.setRating(foodScore);

			// submit rating
			Button btnSubmitFood = (Button) dialogRate
					.findViewById(R.id.btnSubmit);
			btnSubmitFood.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					foodScore = ratingEstab.getRating();
					ratingEstab.setRating(0);
					rateFood.setRating(foodScore);
					dialogRate.dismiss();
				}
			});

			// Hide error
			FrameLayout layoutRateFood = (FrameLayout) findViewById(R.id.layoutFood);
			layoutRateFood.setBackgroundResource(R.drawable.border);

			dialogRate.show();
			break;

		case R.id.layoutOverall:
			dialogRate.setTitle("Rate Overall");
			ratingEstab.setRating(overallScore);

			// submit rating
			Button btnSubmitOverall = (Button) dialogRate
					.findViewById(R.id.btnSubmit);
			btnSubmitOverall.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					overallScore = ratingEstab.getRating();
					ratingEstab.setRating(0);
					rateOverall.setRating(overallScore);
					dialogRate.dismiss();
				}
			});

			// Hide error
			FrameLayout layoutRateOverall = (FrameLayout) findViewById(R.id.layoutOverall);
			layoutRateOverall.setBackgroundResource(R.drawable.border);

			dialogRate.show();
			break;

		case R.id.layoutTime:
			dialogTime.setTitle("Set Time");
			dialogTime.show();
			break;

		case R.id.layoutMeal:
			dialogMeal.setTitle("Meal Option                   ");
			dialogMeal.show();
			break;

		case R.id.layoutCost:
			dialogCost.setTitle("Set Cost");
			dialogCost.show();
			break;

		case R.id.btnSave:
			// Check all field rating
			if (!checkAllFieldRating())
				return;

			dialogWaiting = ProgressDialog.show(this, "Loading",
					"Saving Advance Details");
			
			Thread th = new Thread(new Runnable() {
				public void run() {
					// Get comments
					EditText edtComments = (EditText) findViewById(R.id.edtComments);
					comments = edtComments.getText().toString();

					// Add details to Establishment
					estab.setDateReview(date);
					estab.setTypeOfMeal(typeOfMeal);
					estab.setCost(cost);
					estab.setRateService(serviceScore);
					estab.setRateAtmosphere(atmosphereScore);
					estab.setRateFood(foodScore);
					estab.setRateOverall(overallScore);
					estab.setComment(comments);
					resultUpdate = estabDataSource.updateEstablishment(estab);

					handler.post(new Runnable() {
						public void run() {
							if (resultUpdate) {
								// Hide Button Save and Cancel
								layoutBtnSaveAndCancel.setVisibility(LinearLayout.GONE);
								displayInfo();
								Toast.makeText(DetailsEstablishment.this, "update successful", Toast.LENGTH_SHORT)
										.show();
							} else {
								Toast.makeText(DetailsEstablishment.this, "update unsuccessful", Toast.LENGTH_SHORT)
										.show();
							}
						}
					});
					dialogWaiting.dismiss();
				}
			});
			th.start();
			break;

		case R.id.btnCancel:
			layoutAdvanceDetails.setVisibility(LinearLayout.GONE);
			layoutBtnSaveAndCancel.setVisibility(LinearLayout.GONE);
			layoutBtnAddAdvance.setVisibility(LinearLayout.VISIBLE);
			break;
		default:
			break;
		}
	}

	private boolean checkAllFieldRating() {
		if (serviceScore == 0 || atmosphereScore == 0 || foodScore == 0
				|| overallScore == 0) {
			if (serviceScore == 0) {
				FrameLayout layoutRateService = (FrameLayout) findViewById(R.id.layoutService);
				layoutRateService.setBackgroundResource(R.drawable.error);
			}

			if (atmosphereScore == 0) {
				FrameLayout layoutRateAtmosphere = (FrameLayout) findViewById(R.id.layoutAtmosphere);
				layoutRateAtmosphere.setBackgroundResource(R.drawable.error);
			}

			if (foodScore == 0) {
				FrameLayout layoutRateFood = (FrameLayout) findViewById(R.id.layoutFood);
				layoutRateFood.setBackgroundResource(R.drawable.error);
			}

			if (overallScore == 0) {
				FrameLayout layoutRateOverall = (FrameLayout) findViewById(R.id.layoutOverall);
				layoutRateOverall.setBackgroundResource(R.drawable.error);
			}

			// Notify to view
			Toast.makeText(this, "Pleased rate all", Toast.LENGTH_LONG).show();
			return false;
		} else
			return true;
	}

	private void cancelDialogClicked() {
		// Cancel Rate
		Button btnCancelRate = (Button) dialogRate.findViewById(R.id.btnCancel);
		btnCancelRate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialogRate.dismiss();
				ratingEstab.setRating(0);
			}
		});

		// Cancel Time
		Button btnCancelTime = (Button) dialogTime.findViewById(R.id.btnCancel);
		btnCancelTime.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialogTime.dismiss();
			}
		});

		// Cancel Meal
		Button btnCancelMeal = (Button) dialogMeal.findViewById(R.id.btnCancel);
		btnCancelMeal.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				dialogMeal.dismiss();
			}
		});

		// Cancel Cost
		Button btnCancelCost = (Button) dialogCost.findViewById(R.id.btnCancel);
		btnCancelCost.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				dialogCost.dismiss();
			}
		});
	}

	private void setTime() {
		Button btnSet = (Button) dialogTime.findViewById(R.id.btnSet);
		btnSet.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				DatePicker dateEstab = (DatePicker) dialogTime
						.findViewById(R.id.dateEstab);
				date = Integer.toString(dateEstab.getDayOfMonth()) + "/"
						+ Integer.toString(dateEstab.getMonth() + 1) + "/"
						+ Integer.toString(dateEstab.getYear());
				txtDate.setText(date);
				dialogTime.dismiss();
			}
		});
	}

	private void selectTypeOfMeal() {
		Button btnSelectMeal = (Button) dialogMeal.findViewById(R.id.btnSelect);
		btnSelectMeal.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				RadioGroup rg = (RadioGroup) dialogMeal
						.findViewById(R.id.rgMeal);
				RadioButton radioSelected = (RadioButton) dialogMeal
						.findViewById(rg.getCheckedRadioButtonId());
				typeOfMeal = radioSelected.getText().toString();
				txtMeal.setText(typeOfMeal);
				dialogMeal.dismiss();
			}
		});
	}

	private void setCost() {
		Button btnSetCost = (Button) dialogCost.findViewById(R.id.btnSet);
		btnSetCost.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				EditText edtCost = (EditText) dialogCost
						.findViewById(R.id.edtCost);
				txtCost.setText(edtCost.getText() + " US$");
				txtCost.setVisibility(TextView.VISIBLE);// Show cost
				txtCost1.setText(edtCost.getText() + " US$");
				cost = Float.parseFloat(edtCost.getText().toString());
				dialogCost.dismiss();
			}
		});
	}

	private void enableRateClick(boolean check) {
		FrameLayout layoutRateService = (FrameLayout) findViewById(R.id.layoutService);
		layoutRateService.setClickable(check);

		FrameLayout layoutRateAtmosphere = (FrameLayout) findViewById(R.id.layoutAtmosphere);
		layoutRateAtmosphere.setClickable(check);

		FrameLayout layoutRateFood = (FrameLayout) findViewById(R.id.layoutFood);
		layoutRateFood.setClickable(check);

		FrameLayout layoutRateOverall = (FrameLayout) findViewById(R.id.layoutOverall);
		layoutRateOverall.setClickable(check);

		FrameLayout layoutDate = (FrameLayout) findViewById(R.id.layoutTime);
		layoutDate.setClickable(check);

		FrameLayout layoutMeal = (FrameLayout) findViewById(R.id.layoutMeal);
		layoutMeal.setClickable(check);
	}

	private String getDateNow() {
		Calendar currentDate = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat("d/M/yyyy");
		String dateNow = formatter.format(currentDate.getTime());
		System.out.println("Now the date is :=>  " + dateNow);
		return dateNow;
	}
}
